//
//  BSLGalleryHelper.m
//  demo
//
//  Created by RYAN on 15/7/13.
//
//

#import "BSLGalleryHelper.h"
#import "CDVInvokedUrlCommand.h"

@implementation BSLGalleryHelper

+ (instancetype)shareInatance{
    static BSLGalleryHelper *_instance;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        _instance = [[BSLGalleryHelper alloc] init];
        _instance.isAnimated = YES;
        _instance.filter = @"image";
        
    });
    
    return _instance;
}

- (void)setPropertyWithCommand:(CDVInvokedUrlCommand *)command{
    NSString *fileName = [command argumentAtIndex:0 withDefault:nil];
    [self setupFilePath:fileName];
    
    NSString *filter = [command argumentAtIndex:1 withDefault:@"image"];
    if (![filter isEqualToString:@"image"]){
        filter = [filter lowercaseString];//变小写
    }
    
    self.filter = filter;
    
    NSNumber *animation = [command argumentAtIndex:2 withDefault:@YES];
    self.isAnimated = [animation boolValue];
    
    NSDictionary *popoverOptions = [command argumentAtIndex:3 withDefault:nil];
    self.popoverOptions = popoverOptions;
    
    NSNumber *shouldMulti = [command argumentAtIndex:4 withDefault:@NO];
    self.shouldMultiple = [shouldMulti boolValue];
}

- (void)setupFilePath:(NSString *)fileName{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *appName = [infoDic objectForKey:@"CFBundleDisplayName"];
    path = [path stringByAppendingPathComponent:appName];
    
    if (fileName.length && (NSNull *)fileName != [NSNull null]) {
        NSString *tempPath = [self findDirectoryFromPath:fileName];
        
        if (tempPath) {
            path = [path stringByAppendingPathComponent:tempPath];
        }
    }
    
    NSFileManager *fManager = [NSFileManager defaultManager];
    self.fileDirectory = path;
    
    if (![fManager fileExistsAtPath:path]) {
        [fManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

//找出前端传入参数filename是否包含文件夹，有则在沙盒Library/bsl/下创建
//若包含文件名，记录要保存文件的文件后缀
- (NSString *)findDirectoryFromPath:(NSString *)filePath{
    NSString *directory;
    
    if ([filePath rangeOfString:@".png" options:NSCaseInsensitiveSearch].location != NSNotFound ||
        [filePath rangeOfString:@".jpeg" options:NSCaseInsensitiveSearch].location != NSNotFound ||
        [filePath rangeOfString:@".jpg" options:NSCaseInsensitiveSearch].location != NSNotFound) {
        //有文件后缀
        NSRange range = [filePath rangeOfString:@"/" options:NSBackwardsSearch];
        
        if (range.location != NSNotFound) {

            NSString *directoryStr = [filePath substringToIndex:range.location];
            directory = directoryStr;
            NSString *fileStr = [filePath substringFromIndex:range.location + 1];
            self.fileComponent = fileStr;
        }
        
        else{
            //只有文件后缀
            directory = nil;
            self.fileComponent = filePath;
        }
    }

    else{
        directory = filePath;
        self.fileComponent = nil;
    }
    
    if (self.fileComponent) {
        NSRange range = [self.fileComponent rangeOfString:@"."];
        self.filePathExtension = [self.fileComponent substringFromIndex:range.location + 1];
    }
    
    return directory;
    
}

- (BOOL)isPNGPathExtension{
    return ([self.filePathExtension isEqualToString:@"PNG"] || [self.filePathExtension isEqualToString:@"png"]);
}

- (ALAssetsFilter *)groupFilter{
    ALAssetsFilter *assetsFilter;
//    if ([self.filter isEqualToString:@"video"]) {
//        assetsFilter = [ALAssetsFilter allVideos];
//    }
//    
//    else if ([self.filter isEqualToString:@"none"]){
//        assetsFilter = [ALAssetsFilter allAssets];
//    }
//    
//    else{
//        assetsFilter = [ALAssetsFilter allPhotos];
//    }
    assetsFilter = [ALAssetsFilter allPhotos];//暂时只有图片有效
    return assetsFilter;
}

- (NSString *)titleFromFilter{
    NSString *title;
    if ([self.filter isEqualToString:@"video"]) {
        
        title = @"视频";
    }
    
    else if ([self.filter isEqualToString:@"none"]){
        
        title = @"相册";
    }
    
    else{
        title = @"照片";
    }
    return title;
}

- (NSMutableArray *)saveToLibrary:(NSMutableArray *)assets{
    NSMutableArray *libraryPaths = [NSMutableArray array];
    NSString *path = self.fileDirectory;
    
    for (int i=0; i<assets.count; i++) {
        
        BSLAsset *asset = [assets objectAtIndex:i];
        NSData *data = [asset dataWithFullResolutionImage];
        
        NSString *imgName = [asset filename];
        
        if (assets.count == 1 && self.fileComponent) {
            imgName = self.fileComponent;
        }
        
        NSString *filePath = [path stringByAppendingPathComponent:imgName];
        
        if (data && [data writeToFile:filePath atomically:YES]) {
            [libraryPaths addObject:filePath];
        }
    }
    
    return libraryPaths;
}

- (BOOL)popoverSupported{
    return (self.popoverOptions != nil) && (NSClassFromString(@"UIPopoverController") != nil) &&
    (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad);
}

- (CGRect)getPoppverControllerFrame{
    if (![self popoverSupported]) {
        return CGRectZero;
    }
    
    NSInteger x = 0;
    NSInteger y = 32;
    NSInteger width = 320;
    NSInteger height = 480;
    UIPopoverArrowDirection arrowDirection = UIPopoverArrowDirectionAny;
    
    NSDictionary *options = self.popoverOptions;
    if (options) {
        x = [self integerValueForKey:options key:@"x" defaultValue:0];
        y = [self integerValueForKey:options key:@"y" defaultValue:32];
        width = [self integerValueForKey:options key:@"width" defaultValue:320];
        height = [self integerValueForKey:options key:@"height" defaultValue:480];
        arrowDirection = [self integerValueForKey:options key:@"arrowDir" defaultValue:UIPopoverArrowDirectionAny];
    }
    return CGRectMake(x, y, width, height);
}

- (NSInteger)integerValueForKey:(NSDictionary*)dict key:(NSString*)key defaultValue:(NSInteger)defaultValue
{
    NSInteger value = defaultValue;
    
    NSNumber* val = [dict valueForKey:key];  // value is an NSNumber
    
    if (val != nil) {
        value = [val integerValue];
    }
    return value;
}

@end
